<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Webservice extends CI_Controller {

    public function Webservice() {
        parent::__construct();

        $this->load->model('user_model', 'user');
        $this->load->model('host_model', "host");
        $this->load->model('zone_model', "zone");
    }

    public function index() {
        
    }

    public function getip() {
        $return = array(
            "ip" => $_SERVER['REMOTE_ADDR'],
        );
        $json = json_encode($return);
        header('Content-Type: application/json');
        echo $json;
    }

    public function gethosts() {
        if (!isset($_SERVER['PHP_AUTH_USER'])) {
            header('WWW-Authenticate: Basic realm="Engelsoft"');
            header('HTTP/1.0 401 Unauthorized');
            echo 'Autenticacao nessessaria!';
            exit;
        } else {
            $loginname = $_SERVER['PHP_AUTH_USER'];
            $loginpw = $_SERVER['PHP_AUTH_PW'];

            $loginname = strtolower($loginname);

            $user = $this->user->login($loginname);

            if ($user->password == md5($loginname . $loginpw)) {

                $hosts = $this->host->myhosts($user->id);
                $json = json_encode($hosts);
                header('Content-Type: application/json');
                echo $json;
            } else {
                $logininfo = array(
                    "loged" => 0,
                );

                $json = json_encode($logininfo);
                header('Content-Type: application/json');
                echo $json;
            }
        }
    }

    public function dologin() {
        if (!isset($_SERVER['PHP_AUTH_USER'])) {
            header('WWW-Authenticate: Basic realm="Engelsoft"');
            exit;
        } else {
            $loginname = $_SERVER['PHP_AUTH_USER'];
            $loginpw = $_SERVER['PHP_AUTH_PW'];

            $loginname = strtolower($loginname);

            $user = $this->user->login($loginname);

            if ($user && $user->password == md5($loginname . $loginpw)) {

                $logininfo = array(
                    "loginid" => $user->id,
                    "login" => $user->login,
                    "username" => $user->name,
                    "loged" => 1,
                );

                $json = json_encode($logininfo);
                header('Content-Type: application/json');
                echo $json;
            } else {
                $logininfo = array(
                    "loged" => 0,
                    "error" => "wrong user password combination",
                );

                $json = json_encode($logininfo);
                header('Content-Type: application/json');
                echo $json;
            }
        }
    }

    public function dohostupdate() {
        if (!isset($_SERVER['PHP_AUTH_USER'])) {
            header('WWW-Authenticate: Basic realm="Engelsoft"');
            header('HTTP/1.0 401 Unauthorized');
            $jsonresponse = array(
                "updated" => 0,
                "updated" => "Login failed",
            );

            $json = json_encode($jsonresponse);
            header('Content-Type: application/json');
            echo $json;
            exit;
        } else {
            $loginname = $_SERVER['PHP_AUTH_USER'];
            $loginpw = $_SERVER['PHP_AUTH_PW'];

            $loginname = strtolower($loginname);

            $user = $this->user->login($loginname);

            if ($user->password == md5($loginname . $loginpw)) {

                $post = file_get_contents('php://input');
                if ($post) {
                    $json = json_decode($post);

                    if ($json->hosts) {
                        $ipsrv = $_SERVER['REMOTE_ADDR'];

                        $ip = $json->ip;

//                      verifica variaveis necessárias
                        if ($ip && $ipsrv && $ip == $ipsrv) {
                            if ($json->hosts) {
                                $hosts = $json->hosts;
                                foreach ($hosts as $value) {
                                    $host = $this->host->host($value);

//                                  verifica se o usuario é dono do host
                                    if ($user->id == $host->user) {
                                        if ($host->ip != $ip) {
                                            $this->host->update($host->id, false, false, $ip);
                                        }
                                    } else {
                                        $jsonresponse = array(
                                            "updated" => 0,
                                            "msg" => "Access denied!",
                                        );
                                    }
                                }
                                $jsonresponse = array(
                                    "updated" => 1,
                                    "msg" => "Atualizado",
                                );
                            } else {
                                $jsonresponse = array(
                                    "updated" => 1,
                                    "msg" => "Sem mudanças",
                                );
                            }
                        } else {
                            $jsonresponse = array(
                                "updated" => 0,
                                "msg" => "Missing data!",
                            );
                        }
                    } else {
                        $jsonresponse = array(
                            "updated" => 0,
                            "msg" => "Missing data!",
                        );
                    }


                    $json = json_encode($jsonresponse);
                    header('Content-Type: application/json');
                    echo $json;
                } else {
                    $jsonresponse = array(
                        "updated" => 0,
                        "msg" => "You must send more info to make this update",
                    );

                    $json = json_encode($jsonresponse);
                    header('Content-Type: application/json');
                    echo $json;
                }
            } else {
                $jsonresponse = array(
                    "updated" => 0,
                    "msg" => "Login error",
                );

                $json = json_encode($jsonresponse);
                header('Content-Type: application/json');
                echo $json;
            }
        }
    }

    public function ddnsupdate() {
        if (!isset($_SERVER) || !isset($_SERVER['PHP_AUTH_USER'])) {
            header('WWW-Authenticate: Basic realm="Engelsoft"');
            header('HTTP/1.0 401 Unauthorized');
            echo "badauth";
            exit;
        } else {
            $loginname = $_SERVER['PHP_AUTH_USER'];
            $loginpw = $_SERVER['PHP_AUTH_PW'];

            $loginname = strtolower($loginname);

            $user = $this->user->login($loginname);
            if ($user) {
                if ($user->password == md5($loginname . $loginpw)) {

                    $ipsrv = $_SERVER['REMOTE_ADDR'];
                    $hostname = $this->input->get('hostname');
                    $ip = $this->input->get('myip');

//                      verifica variaveis necessárias
                    if ($ip && $ipsrv && $ip == $ipsrv) {
                        if ($hostname) {
                            $hostnamearr = explode('.', $hostname);

                            $zone = '';
                            $primeiro = true;
                            for ($i = 1; $i < count($hostnamearr); $i++) {
                                if (!$primeiro) {
                                    $zone.='.';
                                } else {
                                    $primeiro = false;
                                }
                                $zone.=$hostnamearr[$i];
                            }

                            echo $zone;
                            echo $hostnamearr[0];

                            $host = $this->host->host($hostnamearr[0]);

//                                  verifica se o usuario é dono do host
                            if ($user->id == $host->user) {
                                if ($host->ip != $ip) {
                                    $this->host->update($host->id, false, false, $ip);
                                }
                            } else {
                                echo "denied";
                            }
                            echo "ok";
                        } else {
                            echo "nochng";
                        }
                    } else {
                        echo "nohost";
                    }
                } else {
                    header('HTTP/1.0 401 Unauthorized');
                    header('Content-Type:"text/html"');
                    echo "badauth";
                }
            } else {
                header('HTTP/1.0 401 Unauthorized');
                header('Content-Type:"text/html"');
                echo "badauth";
            }
        }
        $saida = '';
        $saida .= "\n" . ' -- ' . "\n";
        $saida .= print_r($_SERVER, true);
        $saida .= ' -- ' . "\n";

        if ($fp = fopen('/home/servidor/www/dyndns/saida.txt', 'w+')) {
            fwrite($fp, $saida);
            fclose($fp);
        }
    }

}
